<template>
  <el-drawer
    :title="drawerTitle[drawerType]"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    custom-class="tag-drawer tag-enroll-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap" :class="{ disabled: !editable || requireStatus === '2' }" v-loading="loading">
      <div class="drawer-content tag-scrollbar">
        <!-- <div class="single-btn">
        <el-button type="primary" plain round>从我的客群导入</el-button>
        <el-button type="primary" plain round>查看需求范例</el-button>
      </div> -->

        <el-form :model="editForm" label-width="0" :rules="editFormRules" ref="editForm">
          <el-row :gutter="20">
            <el-col :span="12" :offset="6">
              <div class="tag-name">
                <div class="star"></div>
                <el-form-item prop="tagNm">
                  <el-select
                    v-model="editForm.tagId"
                    filterable
                    remote
                    :remote-method="getTagNm"
                    v-if="drawerType === 'add' && changeTag"
                  >
                    <el-option
                      v-for="item in tagList"
                      :key="item.tagId"
                      :label="item.tagNm"
                      :value="item.tagId"
                    ></el-option>
                  </el-select>
                  <el-input
                    placeholder="请输入标签名称"
                    v-model="editForm.tagNm"
                    :disabled="!editable || requireStatus === '2'"
                    v-else
                  ></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="6" align="right">
              <el-switch
                v-model="changeTag"
                inactive-text="新增标签"
                active-text="标签改造"
                :disabled="drawerType === 'edit'"
              ></el-switch>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="star"></div>
                <div class="row1-left linear-purpose">
                  <icon-svg name="iconHq"></icon-svg>
                  统计粒度
                </div>
                <div class="row1-content hq-content">
                  <el-form-item prop="hqTag">
                    <el-radio-group
                      v-model="editForm.hqTag"
                      :disabled="!editable || requireStatus === '2'"
                      class="tag-scrollbar"
                    >
                      <el-radio v-for="item in $dictList('is_hq_tag')" :key="item.key" :label="item.key">
                        {{ item.value }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="star"></div>
                <div class="row1-left linear-purpose">
                  <icon-svg name="iconClient"></icon-svg>
                  客户统计范围
                </div>
                <div class="row1-content hq-content">
                  <el-form-item prop="clientStatRange">
                    <el-radio-group
                      v-model="editForm.clientStatRange"
                      :disabled="!editable || requireStatus === '2'"
                      class="tag-scrollbar"
                    >
                      <el-radio v-for="item in $dictList('client_stat_range')" :key="item.key" :label="item.key">
                        {{ item.value }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="star"></div>
                <div class="row1-left linear-blue">
                  <icon-svg name="iconKind"></icon-svg>
                  标签类别
                </div>
                <div class="row1-content">
                  <el-form-item prop="tagKind">
                    <el-radio-group
                      v-model="editForm.tagKind"
                      :disabled="!editable || requireStatus === '2'"
                      class="tag-scrollbar"
                    >
                      <el-radio v-for="item in $dictList('tag_kind')" :key="item.key" :label="item.key">
                        {{ item.value }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="star"></div>
                <div class="row1-left linear-blue">
                  <icon-svg name="iconRequirePlatform"></icon-svg>
                  标签上线平台
                </div>
                <div class="row1-content">
                  <el-form-item prop="appPlfmId">
                    <el-select v-model="editForm.appPlfmId" multiple :disabled="!editable || requireStatus === '2'">
                      <el-option
                        v-for="item in platforms"
                        :key="item.appPlfmId"
                        :label="item.appPlfmNm"
                        :value="item.appPlfmId.toString()"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="row1-left linear-cyan">
                  <icon-svg name="iconUserName"></icon-svg>
                  IT接口人员
                </div>
                <div class="row1-content hq-content">
                  <el-form-item prop="interfaceStaff">
                    <el-input
                      v-model="editForm.interfaceStaff"
                      placeholder="请输入IT接口人员"
                      :disabled="!editable || requireStatus === '2'"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="row1 clearfix">
                <div class="row1-left linear-cyan">
                  <icon-svg name="iconLimit"></icon-svg>
                  使用限制
                </div>
                <div class="row1-content hq-content">
                  <el-form-item prop="orgId">
                    <el-select v-model="editForm.orgId" :disabled="!editable || requireStatus === '2'">
                      <el-option label="---" value=""></el-option>
                      <el-option label="公有" :value="0"></el-option>
                      <el-option
                        v-for="item in $dictList('org_id')"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="card row2">
                <div class="star"></div>
                <div class="title">
                  <icon-svg name="iconStory"></icon-svg>
                  <div>
                    标签故事
                    <el-tooltip
                      effect="dark"
                      content="示例：根据考核口径客户开卡首次动账后计入当年新获客，作为中后台人员，我希望在新户百日线上经营中以客户首次动账作为起点进入新户客户旅程，以避免有限的线上触达资源浪费"
                      placement="top"
                      popper-class="require-tooltip"
                    >
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                </div>
                <div class="content blue">
                  <el-form-item prop="tagStory">
                    <el-input
                      placeholder="请输入标签故事"
                      v-model="editForm.tagStory"
                      type="textarea"
                      :maxlength="1000"
                      :rows="5"
                      :show-word-limit="true"
                      :disabled="!editable || requireStatus === '2'"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="card row2">
                <div class="star"></div>
                <div class="title">
                  <icon-svg name="iconBizstmt"></icon-svg>
                  <div>
                    业务口径
                    <el-tooltip
                      effect="dark"
                      content="示例：新户首次动账日期：按一级分行本部/二级分行统计客户最早一次动账的日期，包括主动动账和被动动账"
                      placement="top"
                      popper-class="require-tooltip"
                    >
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                </div>
                <div class="content blue">
                  <el-form-item prop="bizStmt">
                    <el-input
                      placeholder="请输入业务口径"
                      v-model="editForm.bizStmt"
                      type="textarea"
                      :maxlength="1000"
                      :rows="5"
                      :show-word-limit="true"
                      :disabled="!editable || requireStatus === '2'"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="card row2">
                <div class="title">
                  <icon-svg name="iconItstmt"></icon-svg>
                  <div>
                    技术口径
                    <el-tooltip
                      effect="dark"
                      content="示例：时点AUM首次>=0的日期"
                      placement="top"
                      popper-class="require-tooltip"
                    >
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </div>
                </div>
                <div class="content blue">
                  <el-form-item prop="itStmt">
                    <el-input
                      placeholder="请输入技术口径"
                      v-model="editForm.itStmt"
                      type="textarea"
                      :maxlength="3000"
                      :rows="5"
                      :show-word-limit="true"
                      :disabled="!editable || requireStatus === '2'"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns" v-if="editable" v-loading="loading">
      <el-button @click="handleCancel">取消</el-button>
      <template v-if="requireStatus === '2'">
        <el-button type="warning" size="medium" @click="handleReject">驳回</el-button>
        <el-button type="primary" size="medium" @click="handleAgree">同意</el-button>
      </template>
      <template v-else>
        <el-button type="warning" size="medium" v-if="editable" @click="giveup">删除</el-button>
        <el-button type="primary" size="medium" @click="save(false)" v-if="Number(requireStatus) < 2"
          >保存草稿</el-button
        >
        <el-button type="primary" size="medium" @click="handleSubmit">提交</el-button>
      </template>
    </div>
    <similar-dialog ref="similarDialog" @callback="callbackSimilar"></similar-dialog>
  </el-drawer>
</template>

<script>
import similarDialog from '@/components/tag-similar-dialog'
export default {
  components: {
    similarDialog
  },
  data() {
    return {
      drawerType: 'add',
      drawerTitle: {
        add: '新增需求',
        edit: '需求明细'
      },
      drawerVisible: false,
      editable: false,
      loading: false,
      platforms: [],
      changeTag: false,
      tagList: [],
      changeId: '',
      requireStatus: '',
      editForm: {
        tagId: '',
        requireId: '',
        tagNm: '',
        hqTag: '',
        clientStatRange: '',
        appPlfmId: [],
        tagStory: '',
        bizStmt: '',
        itStmt: '',
        handlerId: '',
        orgId: '',
        interfaceStaff: '',
        tagKind: ''
      },
      editFormRules: {
        hqTag: [{ validator: this.$checkBoolNum('统计粒度必须选择'), trigger: 'change' }],
        clientStatRange: [{ validator: this.$checkBoolNum('客户统计范围必须选择'), trigger: 'change' }],
        tagNm: [
          { required: true, message: '标签名称不能为空', trigger: 'blur' },
          { max: 100, message: '标签名称不能超过100个字符', trigger: 'blur' }
        ],
        appPlfmId: [{ required: true, message: '至少选择一项', trigger: 'change' }],
        tagStory: [
          { required: true, message: '标签故事不能为空', trigger: 'blur' },
          { max: 1000, message: '标签故事不能超过1000个字符', trigger: 'blur' }
        ],
        bizStmt: [
          { required: true, message: '业务口径不能为空', trigger: 'blur' },
          { max: 1000, message: '业务口径不能超过1000个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'editForm.tagId'(val) {
      if (val && this.changeTag) this.getInfo()
    }
  },
  methods: {
    showDrawer(tag) {
      this.getPlatforms()
      if (tag && tag.requireId) {
        this.requireStatus = tag.requireStatus
        this.editForm.requireId = tag.requireId
        this.drawerType = 'edit'
        this.getDetail(tag)
      } else {
        this.editable = true
        this.drawerVisible = true
      }
    },
    getInfo() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagRequireModify/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.initTag(
            Object.assign({}, data.data.tagRequireFProcDTO, {
              requireType: 1
            }),
            true
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getPlatforms() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astAppPlatform/getAll'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.platforms = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astOriginalRequire/${this.editForm.requireId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.initTag(data.data)
          this.drawerVisible = true
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    initTag(tag, isChange = false) {
      this.changeTag = !!tag.requireType
      this.editable = tag.isModify
      this.editForm.tagNm = tag.tagNm
      this.editForm.hqTag = isChange ? tag.hqTagId : tag.hqTag
      this.editForm.clientStatRange = isChange ? tag.clientStatRangeId : tag.clientStatRange
      this.editForm.tagStory = tag.tagStory
      this.editForm.bizStmt = tag.bizStmt
      this.editForm.itStmt = tag.itStmt
      this.editForm.orgId = tag.orgId
      this.editForm.interfaceStaff = tag.interfaceStaff
      this.editForm.tagKind = isChange ? tag.tagKindId : tag.tagKind
      if (isChange) {
        this.editForm.appPlfmId = []
        tag.appPlfms.forEach(item => this.editForm.appPlfmId.push(item.appPlfmId.toString()))
      } else {
        this.editForm.appPlfmId = tag.appPlfmId.split(',')
      }
    },
    handleCancel() {
      this.clearForm()
      this.$nextTick(() => (this.drawerVisible = false))
    },
    getTagNm(query) {
      if (!query) {
        this.tagList = []
        return
      }
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagRequireModify/getTagNmList/${query}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tagList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    clearForm() {
      this.drawerType = 'add'
      this.editable = false
      this.loading = false
      this.changeTag = false
      this.platforms = []
      this.tagList = []
      this.requireStatus = ''
      this.editForm = {
        tagId: '',
        requireId: '',
        tagNm: '',
        appPlfmId: [],
        tagStory: '',
        bizStmt: '',
        itStmt: '',
        handlerId: '',
        hqTag: '',
        clientStatRange: '',
        orgId: '',
        interfaceStaff: '',
        tagKind: ''
      }
      this.$nextTick(() => this.$refs.editForm.clearValidate())
    },
    save(isSubmit = false) {
      let url = isSubmit ? 'ast/astOriginalRequire/originalRequireSubmit' : 'ast/astOriginalRequire/originalRequireSave'
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let itStmt = new Buffer(this.editForm.itStmt).toString('base64')
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl(url),
            method: 'post',
            data: this.$ajax.setData({
              appPlfmId: this.editForm.appPlfmId.join(','),
              bizStmt: this.editForm.bizStmt,
              itStmt: itStmt,
              requireId: this.editForm.requireId,
              requireType: this.changeTag ? 1 : 0,
              tagNm: this.editForm.tagNm,
              tagStory: this.editForm.tagStory,
              hqTag: this.editForm.hqTag,
              clientStatRange: this.editForm.clientStatRange,
              orgId: this.editForm.orgId,
              interfaceStaff: this.editForm.interfaceStaff,
              tagKind: this.editForm.tagKind
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.editForm.requireId = data.data
              this.$message.success(data.msg)
              if (isSubmit) {
                this.beforeClose()
                this.$emit('callback')
              }
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    handleSubmit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.changeTag) {
            this.save(true)
            return
          }
          this.loading = true
          let params = {
            tagName: this.editForm.tagNm,
            tagBizStmt: this.editForm.bizStmt
          }
          this.$ajax({
            url: this.$ajax.setUrl('ast/astTagRequireManager/haveSimRequire'),
            method: 'post',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              if (data.data && data.data.length) this.$refs.similarDialog.showDialog(data.data)
              else this.save(true)
            } else {
              this.$message.error(data.data || data.msg)
              this.loading = false
            }
          })
        }
      })
    },
    callbackSimilar(way) {
      if (!way) this.loading = false
      else if (way === 'save') this.save()
      else this.save(true)
    },
    giveup() {
      this.$confirm(`确定删除原始需求【${this.editForm.tagNm}】？`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astOriginalRequire/deleteRequire/${this.editForm.requireId}`),
          method: 'post',
          data: this.$ajax.setData()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.beforeClose()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    handleReject() {
      this.$confirm(`确定驳回原始需求【${this.editForm.tagNm}】？`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astOriginalRequire/rejectOriginalRequire/${this.editForm.requireId}`),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.beforeClose()
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    handleAgree() {
      this.$confirm(`确定同意原始需求【${this.editForm.tagNm}】？`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astOriginalRequire/agreeOriginalRequire/${this.editForm.requireId}`),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.beforeClose()
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    beforeClose() {
      this.clearForm()
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
        this.drawerVisible = false
        this.$emit('callback')
      })
    }
  }
}
</script>

<style lang="scss">
.tag-drawer.tag-enroll-drawer {
  .el-drawer__body {
    .drawer-wrap {
      &.disabled {
        bottom: 30px;
        border-bottom-left-radius: 20px;
        border-bottom-right-radius: 20px;
      }
      .tag-status-list {
        padding: 10px 0;
        li {
          padding: 10px;
          .el-col {
            word-break: break-all;
            line-height: 25px;
          }
        }
      }
    }
  }
  .single-btn {
    margin: 20px 0;
    .el-button {
      margin-right: 20px;
    }
  }
  .tag-name {
    position: relative;
    .el-input__inner {
      background-color: #fbf5e5;
      border: 1px dashed #faeace;
    }
    .el-switch {
      margin-top: 8px;
    }
  }
  .row1 {
    height: 90px;
    padding: 0 0 10px 200px;
    color: #fff;
    border-radius: 10px;
    border-top-right-radius: 0;
    margin-bottom: 20px;
    line-height: normal;
    box-shadow: #eee 0 0 10px;
    overflow: hidden;
    position: relative;
    .row1-left {
      width: 200px;
      height: 100%;
      line-height: 90px;
      padding: 0 0 10px 20px;
      position: absolute;
      left: 0;
      font-size: 20px;
      svg {
        width: 40px;
        height: 40px;
        vertical-align: middle;
        margin: -10px 5px 0 0;
      }
    }
    .row1-content {
      height: 100%;
      text-align: left;
      padding: 10px;
      padding-left: 20px;
      .el-form-item,
      .el-form-item__content {
        height: 100%;
        line-height: 25px;
      }
      .el-radio-group {
        height: 100%;
        overflow-y: auto;
      }
      .el-radio {
        margin-top: 10px;
      }
      &.hq-content .el-radio {
        margin-top: 25px;
      }
      .el-select {
        margin-top: 15px;
        .el-input {
          margin-top: 0;
        }
      }
      .el-input {
        margin-top: 15px;
      }
    }
    .content {
      font-size: 20px;
      margin-bottom: 10px;
    }
  }
  .row2 {
    margin-bottom: 20px;
    padding: 0 0 0 200px;
    border-bottom: 0;
    position: relative;
    &:before {
      width: 3px;
      height: 50px;
    }
    &:after {
      width: 3px;
      height: 30px;
    }
    .title {
      width: 200px;
      color: $theme-color;
      margin: 2px 0 18px 0;
      text-align: center;
      position: absolute;
      left: 0;
      svg {
        width: 50px;
        height: 50px;
        margin: 20px 0 10px 0;
      }
    }
    .content {
      height: auto;
      min-height: 150px;
      padding: 15px 15px 0 15px;
      text-align: left;
      border-left: 3px solid $border-color;
      position: relative;
      .el-form-item,
      .el-form-item__content {
        height: 100%;
        line-height: 25px;
      }
      .el-checkbox-group {
        height: 100%;
        overflow-y: auto;
      }
      .el-form-item {
        padding-bottom: 10px;
      }
      .el-form-item__error {
        top: calc(100% - 12px);
      }
      &:after {
        width: 3px;
        content: '';
        position: absolute;
        top: 10px;
        left: -3px;
        bottom: 10px;
      }
      &.purpose:after {
        background-color: #a18cf1;
      }
      &.blue:after {
        background-color: #23ace3;
      }
    }
  }
  .drawer-btns .el-loading-spinner svg {
    opacity: 0;
  }
}
.el-tooltip__popper.require-tooltip {
  max-width: 400px;
  line-height: 20px;
}
</style>
